package com.group3.service.mqservice;

import com.group3.Feign.OrderServiceFeign;
import com.group3.common.topic.OrderTopic;
import com.group3.model.Order;
import com.group3.model.Payment;
import com.group3.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Slf4j
@Service
@RocketMQMessageListener(topic = OrderTopic.ORDER_PAY,consumerGroup = "payOrder")
public class PayOrderService implements RocketMQListener<Order> {
    @Autowired
    private OrderServiceFeign orderServiceFeign;

    @Autowired
    private PaymentService paymentService;
    @Override
    public void onMessage(Order o) {
        Order order = orderServiceFeign.getOrderByOid(o.getOid());
        Payment payment = new Payment();
        // 2. 校验订单状态（假设0是未支付状态）
        if (order != null && order.getStatus() == 0) {
            // 3. 更新订单状态为已支付（1是已支付状态）
            order.setStatus(1);
            boolean updateResult = orderServiceFeign.updateOrder(order);
            // 4. 创建支付记录
            if (updateResult) {
                payment.setOid(o.getOid());
                payment.setUid(order.getUid());
                payment.setUsername(order.getUsername());
                payment.setPid(order.getPid());
                payment.setPname(order.getPname());
                payment.setPprice(order.getPprice());
                payment.setNumber(order.getNumber());
                payment.setTotal(order.getPprice() * order.getNumber()); // 计算总金额
                payment.setStatus(1); // 设置支付状态为已支付
                paymentService.save(payment);
            }
            log.info("支付成功{}", payment);
        }
    }
}
